package com.hu.common.util.user;


import com.hu.common.config.Config;
import com.hu.common.constants.Time;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * jwt帮助类
 *
 * @Author: 63198
 * @Date: 2019/5/20 9:42 AM
 * @Version 1.0
 */
public class JwtUtil {

    private static String key = "com.mychery.awesomeproject.123!@#";

    public static String JWT_HEADER_FLAG = "Bearer ";


    /**
     * 创建token 默认10分钟
     *
     * @param subject
     * @return
     */
    public static String createToken(String subject) {
        Integer duration = Config.userTokenDuration;
        return createToken(subject, duration * Time.MINUTE);
    }

    /**
     * 创建token
     *
     * @param subject
     * @param duration 过期时间
     * @return
     */
    public static String createToken(String subject, long duration) {

        String token = Jwts.builder()
                .setSubject(subject)
                .setExpiration(new Date(System.currentTimeMillis() + duration))
                .signWith(SignatureAlgorithm.HS512, key)
                .compact();
        return token;
    }

    public static String parseToken(String token) {
        String subject = Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(token.replace(JWT_HEADER_FLAG, ""))
                .getBody()
                .getSubject();
        return subject;
    }
}
